package com.abl.core.service.mt.impl;

import com.abl.core.common.security.AuthUser;
import com.abl.core.common.util.AuthKit;
import com.abl.core.common.ws.handler.TextHandler;
import com.abl.core.domain.db.MtRoomUserAuth;
import com.abl.core.domain.db.SysUser;
import com.abl.core.domain.mt.MtLiveRoomVo;
import com.abl.core.domain.project.MSG;
import com.abl.core.domain.project.SRS;
import com.abl.core.domain.project.ServiceException;
import com.abl.core.mybatis.mapper.MtRoomMapper;
import com.abl.core.mybatis.mapper.MtRoomUserAuthMapper;
import com.abl.core.mybatis.mapper.SysUserMapper;
import com.abl.core.service.mt.MtLiveRoomService;
import com.mybatisflex.core.query.QueryWrapper;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ConcurrentSkipListSet;

import static com.abl.core.domain.db.table.MtRoomUserAuthTableDef.MT_ROOM_USER_AUTH;

/**
 * 会议室内部逻辑
 */
@Service
public class MtMtLiveRoomServiceImpl implements MtLiveRoomService {
    @Resource
    private MtRoomUserAuthMapper roomUserAuthMapper;

    @Resource
    private MtRoomMapper mtRoomMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    //当前房间信息
    @Override
    public MtLiveRoomVo roomInfo(String mtId) {
        return null;
    }

    //同意连麦
    @Override
    public boolean agreeTop(String userId, String mtId) {
        AuthUser authUser = AuthKit.mastLogin();
        MtRoomUserAuth roomUserAuth = roomUserAuthMapper.getById(mtId, authUser.getUserId());
        //非主持人无权操作
        if (!"1".equals(roomUserAuth.getIsCompere())) throw new ServiceException(MSG.ER_403);

        QueryWrapper wrapper = QueryWrapper.create()
                .and(MT_ROOM_USER_AUTH.USER_ID.eq(userId))
                .and(MT_ROOM_USER_AUTH.MT_ID.eq(mtId));
        MtRoomUserAuth mtRoomUserAuth = roomUserAuthMapper.selectOneByQuery(wrapper);

        MtRoomUserAuth update = new MtRoomUserAuth();
        update.setId(mtRoomUserAuth.getId());
        update.setAuthTop("1");
        update.setApplyTopStatus("1");
        roomUserAuthMapper.update(update);
        sendRefreshTopList(mtId);
        return true;
    }

    //强制下麦
    @Override
    public boolean outTop(String userId, String mtId) {
        return refuseTop(userId, mtId);
    }

    //申请连麦
    @Override
    public boolean applyTop(String mtId) {
        AuthUser authUser = AuthKit.mastLogin();

        //查询是否存在
        MtRoomUserAuth mtRoomUserAuth = roomUserAuthMapper.getById(mtId, authUser.getUserId());

        //不存在直接插入，然后推送申请通知
        if (mtRoomUserAuth == null) {
            mtRoomUserAuth = new MtRoomUserAuth();
            mtRoomUserAuth.setUserId(authUser.getUserId());
            mtRoomUserAuth.setMtId(mtId);
            mtRoomUserAuth.setApplyTopStatus("1");
            roomUserAuthMapper.insertSelective(mtRoomUserAuth);
            sendApplyTopMsg(authUser.getUserId(), mtId);
            return true;
        }

        //如果没有资格，发起申请，发送消息
        String authTop = mtRoomUserAuth.getAuthTop();
        if ("0".equals(authTop)) {
            mtRoomUserAuth.setApplyTopStatus("1");
            sendApplyTopMsg(authUser.getUserId(), mtId);
            return true;
        }

        return true;
    }

    //拒绝连麦
    @Override
    public boolean refuseTop(String userId, String mtId) {
        AuthUser authUser = AuthKit.mastLogin();
        MtRoomUserAuth roomUserAuth = roomUserAuthMapper.getById(mtId, authUser.getUserId());
        //非主持人无权操作
        if (!"1".equals(roomUserAuth.getIsCompere())) throw new ServiceException(MSG.ER_403);

        //拒绝连麦，重置字段
        roomUserAuth = new MtRoomUserAuth();
        roomUserAuth.setAuthTop("0");
        roomUserAuth.setApplyTopStatus("0");

        QueryWrapper wrapper = QueryWrapper.create()
                .and(MT_ROOM_USER_AUTH.USER_ID.eq(userId))
                .and(MT_ROOM_USER_AUTH.MT_ID.eq(mtId));
        int i = roomUserAuthMapper.updateByQuery(roomUserAuth, wrapper);
        return true;
    }

    //当前会议中上麦人员信息列表
    @Override
    public List<MtRoomUserAuth> topList(String mtId) {
        AuthKit.mastLogin();

        QueryWrapper wrapper = QueryWrapper.create()
                .and(MT_ROOM_USER_AUTH.MT_ID.eq(mtId));
        List<MtRoomUserAuth> mtRoomUserAuths = roomUserAuthMapper.selectListByQuery(wrapper);

        for (MtRoomUserAuth mtRoomUserAuth : mtRoomUserAuths) {
            SysUser sysUser = sysUserMapper.getColumn(mtRoomUserAuth.getUserId(), "nick_name", "avatar");
            mtRoomUserAuth.setAvatar(sysUser.getAvatar());
            mtRoomUserAuth.setNickName(sysUser.getNickName());
        }

        return mtRoomUserAuths;
    }

    //我的信息
    @Override
    public MtRoomUserAuth myInfo(String mtId) {
        AuthUser authUser = AuthKit.mastLogin();
        MtRoomUserAuth mtRoomUserAuth = roomUserAuthMapper.getById(authUser.getUserId(), mtId);

        SysUser sysUser = sysUserMapper.getColumn(mtRoomUserAuth.getUserId(), "nick_name", "avatar");
        mtRoomUserAuth.setAvatar(sysUser.getAvatar());
        mtRoomUserAuth.setNickName(sysUser.getNickName());

        return mtRoomUserAuth;
    }

    //通知房主有人申请上麦
    @Override
    public void sendApplyTopMsg(String applyUserId, String mtId) {
        String roomUserId = mtRoomMapper.getRoomUserId(mtId);
        QueryWrapper wrapper = QueryWrapper.create()
                .select("nick_name", "id")
                .and("id=?", applyUserId);
        SysUser applyUser = sysUserMapper.selectOneByQuery(wrapper);

        SRS<Object> result = SRS.bySuccess(applyUser);
        result.set("type", "applyTop");
        result.set("mtId", mtId);

        //通知房主
        Channel channel = TextHandler.channelAll.get("PHONE" + roomUserId);
        channel.writeAndFlush(new TextWebSocketFrame(result.toJSONString()));
    }

    //通知所房间连麦人数变更
    @Override
    public void sendRefreshTopList(String mtId) {
        List<MtRoomUserAuth> mtRoomUserAuths = topList(mtId);
        SRS<Object> result = SRS.bySuccess(mtRoomUserAuths);
        result.set("type", "refreshTopList");
        result.set("mtId", mtId);

        //通知所有人刷新
        ConcurrentSkipListSet<Channel> channels = TextHandler.mtAll.get(mtId);
        for (Channel channel : channels) {
            channel.writeAndFlush(new TextWebSocketFrame(result.toJSONString()));
        }
    }


}
